package com.mrzhou.mybatis.support;

import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Getter
@Setter
public class ParentTree<T> {

    /**
     * 根节点标识
     */
    public static final Long PARENT_ID_FLAG = 0L;

    private Long id;

    @ApiModelProperty("父级菜单id")
    private Long parentId;

    @ApiModelProperty("子菜单")
    private List<T> children;

    public List<T> getChildren() {
        if (null == this.children) {
            this.children = new ArrayList<>();
        }
        return this.children;
    }

    /**
     * 处理层级结构数据
     * @param list
     * @param <T>
     * @return
     */
    public static <T extends ParentTree> List<T> convertListToTree(List<T> list) {
        if (null != list) {
            // 排除集合中的空数据
            List<T> nonNullList = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
            nonNullList.stream().forEach(var -> {
                if (!var.getParentId().equals(PARENT_ID_FLAG)) {
                    // 查找父级id
                    nonNullList.stream().filter(parent -> var.getParentId().equals(parent.getId())).findFirst().ifPresent(vo -> {
//                        vo.setHasChildren(true);
                        vo.getChildren().add(var);
                    });
                }
            });
            return nonNullList.stream().filter(var -> var.getParentId().equals(PARENT_ID_FLAG)).collect(Collectors.toList());
        }
        return list;
    }

}